# fileOperationPractice


'1、接受用户的输入并保存为新的文件'
def acceptEnterSaveFile():
    filename = input('请输入文件名：')
    with open(filename, 'a') as target:
        print('请输入要写入的文件，单独按q退出：')
        while 1:
            line = input()
            if line != 'q':
                target.write('%s\n' % line)
            else:
                break


'2、复制文件,非文本文件必须使用二进制格式读取和写入（b)'
def copyFile():
    with open('e:/1.txt', 'rb') as target:
        f = target.read()
    with open('e:/2.txt', 'wb') as target:
        target.write(f)


'3、比较用户输入的两个文件、如果不同显示出所有不同处的行号与第一个不同字符的位置'
def fileDifference(file1, file2):
    with open(file1, encoding='utf-8') as target:
        f = open(file2, encoding='utf-8')
        row = 0
        lan = target.readline()
        lan2 = f.readline()
        while lan != '':
            row += 1
            if lan2 != lan:
                print('%i行' % row, end='')
                for i in range(len(lan2)):
                    if lan[i] != lan2[i]:
                        print('第%i个字符不同:' % i)
                        break
                print(lan2, lan)
            lan = target.readline()
            lan2 = f.readline()
'调用例子'
# fileDifference('e:/1.txt','e:/2.txt')


'4、编写一个程序，当用户输入文件名和行数(N)后将该文件的前N行打印到当前屏幕上'
def printBeforeRow():
    fileName = input('请输入要打开的文件（c:\\test.txt）:')
    rowNumber = int(input('请输入需要显示该文件的前几行：'))
    print('文件%s的前%d的内容如下:' % (fileName, rowNumber))
    with open(fileName) as target:
        for i in range(rowNumber):
            print(target.readline(), end='')


'5、上题扩展，要求输入指定行数，如13-21行、：21打印前21行、21：打印21行到结尾'
def printBeforeEndRow():
    fileName = input('请输入要打开的文件（c:\\test.txt）:')
    rowNumber = input('请输入需要显示的行数【格式如13：21或：21或21：】')
    start = 0
    end = 0
    with open(fileName, encoding='utf-8') as target:
        flist = target.readlines()
        if rowNumber[0] == ':':
            list1 = rowNumber.split(':')
            end = int(list1[1])
            print('文件%s从开始到第%d行的内容如下：' % (fileName, end))
            for i in range(0, end):
                print(flist[i], end='')
        elif rowNumber[-1] == ':':
            list1 = rowNumber.split(':')
            start = int(list1[0])
            end = len(flist)-start
            print('文件%s从第%d行到结束的内容如下：' % (fileName, start))
            for i in range(start, end):
                print(flist[start], end='')
                start += 1
        else:
            list1 = rowNumber.split(':')
            start = int(list1[0])
            end = int(list1[1])
            print('文件%s从第%d行到第%d的内容如下：' % (fileName, start, end))
            for i in range(start, end):
                print(flist[start], end='')
                start += 1


'6、查找文件实现全部替换所查找文字的功能'
def fileFindReplace():
    fileName = input('请输入文件名：')
    with open(fileName, encoding='utf-8') as target:
        fileRow = target.readlines()
        count = 0
        needReplaceWord = input('请输入需要替换的单词或字符：')
        for line in fileRow:
            if line.find(needReplaceWord) != -1:  # find字符串查找函数返回str中第一次出现的substr的第一个字母的标号
                count += 1
                print(line, count)
        print('文件【%s】中共有【%d】个【%s】' % (fileName, count, needReplaceWord))
    newWord = input('请输入新的单词或字符:')
    print('您确定要把所有的%s替换为%s吗？' % (needReplaceWord, newWord))
    isReplace = input('[YES/NO]:')
    lines=[]
    if isReplace == 'YES':
        with open(fileName, encoding='utf-8') as target:
            for line in target.readlines():
                if line.find(needReplaceWord) < 0:
                    lines.append(line)
                else:
                    line=line.replace(needReplaceWord,newWord)  #在line中用newWord替换needReplaceWord，返回替换后的字符串
                    lines.append(line)
        with open(fileName,mode='w',encoding='utf-8')as target:
            target.writelines(lines)
    print('替换成功')

